import {
  CMEVENTS,
  PickedFace,
  pickedFaceData,
  pickedLineData,
  pickedModelData,
} from '@amcax/base';
import { dataManager, userEvents } from '@app-cad/module';
import { Box, Typography } from '@mui/material';
import { Empty } from 'antd';
import { useEffect, useState } from 'react';
import {
  SelectedModels,
  isSimpleSelectedModels,
} from '../utils/SelectedModels';
import MaterialLibAdd from './MaterialLibAdd';
import MaterialLibUpdate from './MaterialLibUpdate';
import MaterialListBox from './MaterialListBox';
import MaterialSetting from './MaterialSetting';

export default function MaterialPanel() {
  const width = 300;
  const [dxid, setDxid] = useState('');
  const [materials, setMaterials] = useState<any[]>([]);
  const [faceIndex, setFaceIndex] = useState(0);
  const [show, setShow] = useState(false);

  useEffect(() => {
    userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: true, width });
    registerSelectionEvents();
    return () => {
      userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: false, width });
    };
  }, []);

  const registerSelectionEvents = () => {
    userEvents.on(
      CMEVENTS.MODELS_SELECTED,
      (selectedModels: SelectedModels) => {
        if (isSimpleSelectedModels(selectedModels)) {
          setupData(selectedModels.values().next().value);
        } else {
          setupData(selectedModels.selectedModels.values().next().value);
        }
      },
    );
    userEvents.on(CMEVENTS.MODEL_SELECTED, (data: pickedModelData) => {
      setupData(data);
    });
    userEvents.on(CMEVENTS.MESH_SELECTED, (data: pickedFaceData) => {
      setupData(data);
    });
    userEvents.on(CMEVENTS.MESH_SELECTED, (data: pickedLineData) => {
      setupData(data);
    });

    userEvents.on(CMEVENTS.MATERIAL_SELECTED, (material: any) => {
      setShow(material != undefined);
    });
  };

  const setupData = (
    data: pickedModelData | pickedFaceData | pickedLineData,
  ) => {
    if (data && data.objInfo) {
      const assisObj = data.assisObj;
      const dxid = data.objInfo.shape;

      const solid = data.objInfo.materials.solid;
      let faces = data.objInfo.materials?.faces ?? [];
      if (solid) {
        faces.push({
          index: -1,
          mat: solid,
        });
      }
      const faceIndex = assisObj instanceof PickedFace ? data.idInfo.i : -1;

      faces = faces.filter((item: any) => {
        return item.index === faceIndex;
      });

      const materials = faces.map(({ index, mat }) => {
        const material = dataManager.getMaterials(mat);
        material['dxid'] = dxid;
        material['faceIndex'] = index;
        return material;
      });
      setDxid(dxid);
      setMaterials(materials);
      setFaceIndex(faceIndex);
      userEvents.emit(CMEVENTS.MATERIAL_MODEL_SELECTED, {
        dxid,
        materials,
        faceIndex,
      });
    } else {
      setDxid('');
      setMaterials([]);
      setFaceIndex(-1);
    }
  };

  return (
    <Box sx={{ p: '20px', width: width + 'px' }}>
      <Typography component='h4'>材质库</Typography>
      {dxid ? (
        <Box
          sx={{ mt: '10px', overflowY: 'auto', width: '100%', height: '100%' }}
        >
          <Box>
            <MaterialListBox
              dxid={dxid}
              materials={materials}
              faceIndex={faceIndex}
            />
          </Box>
          <Box>
            <MaterialLibAdd
              show={!show}
              dxid={dxid}
              materials={materials}
              faceIndex={faceIndex}
            />
          </Box>
          <Box>
            <MaterialLibUpdate
              show={show}
              dxid={dxid}
              materials={materials}
              faceIndex={faceIndex}
            />
          </Box>
          <Box>
            <MaterialSetting
              show={show}
              dxid={dxid}
              materials={materials}
              faceIndex={faceIndex}
            />
          </Box>
        </Box>
      ) : (
        <Box
          sx={{
            mt: '20px',
            overflowY: 'auto',
            width: '250px',
            display: 'flex',
            justifyContent: 'center',
          }}
        >
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description='请选择模型'
          />
        </Box>
      )}
    </Box>
  );
}
